package service

import (
	"github.com/wechaty/go-wechaty/wechaty"
	"github.com/wechaty/go-wechaty/wechaty-puppet/schemas"
	"github.com/wechaty/go-wechaty/wechaty/interface"
	"github.com/wechaty/go-wechaty/wechaty/user"
	"log"
	"palms/model"
	"palms/repository"
	"time"
)

type RobotService interface {

	// List 返回机器人列表
	List(pageNo int, pageSize int) []model.Robot

	// Get 返回机器人信息
	Get(id int64) model.Robot

	// Delete 删除机器人信息
	Delete(id int64)

	GetLoginQrcode() (string, error)

	// MatchAll 匹配一个机器人
	MatchAll(tags []string) ([]model.Robot, error)
}

func NewRobotService(repo repository.RobotRepository) RobotService {
	return &robotService{
		repo: repo,
	}
}

type robotService struct {
	roomService RoomService
	repo        repository.RobotRepository
}

func (s *robotService) MatchAll(tags []string) ([]model.Robot, error) {
	return s.repo.MatchAll(tags)
}

func (s *robotService) List(pageNo int, pageSize int) []model.Robot {
	return s.repo.List(pageNo, pageSize)
}

func (s *robotService) Get(id int64) model.Robot {
	return s.repo.Get(id)
}

func (s *robotService) Delete(id int64) {
	s.repo.Delete(id)
}

var robots map[string]*wechaty.Wechaty

func (s *robotService) GetLoginQrcode() (string, error) {
	var qr string
	var robot = wechaty.NewWechaty().
		OnScan(func(context *wechaty.Context, qrcode string, status schemas.ScanStatus, data string) {
			log.Printf("获得登录二维码[qrcode:%s, status:%d, data:%s]", qrcode, status, data)
			qr = qrcode
		}).
		OnLogin(func(context *wechaty.Context, user *user.ContactSelf) {
			log.Println("微信扫码成功")
			log.Printf("保存微信信息开始[user:%s]\n", user.ID())
			s.save(user)
			log.Printf("保存微信信息结束[user:%s]\n", user.ID())
		}).
		OnLogout(func(context *wechaty.Context, user *user.ContactSelf, reason string) {
			// TODO 机器人下线告警
		}).
		OnFriendship(func(context *wechaty.Context, friendship *user.Friendship) {
			log.Println("收到好友申请")
			err := friendship.Accept()
			if err != nil {
				log.Println("接受好友申请出错")
				return
			}

			if friendship.IsReady() {
				miniProgram := user.NewMiniProgram(&schemas.MiniProgramPayload{
					Appid:       "",
					Username:    "",
					PagePath:    "",
					Description: "",
					ThumbUrl:    "",
					Title:       "",
				})
				_, err := friendship.Contact().Say(miniProgram)
				if err != nil {
					log.Println("发送欢迎小程序失败")
					return
				}
			}
		}).
		OnRoomInvite(func(context *wechaty.Context, roomInvitation *user.RoomInvitation) {
			log.Println("收到入群邀请")
			err := roomInvitation.Accept()
			if err != nil {
				log.Println("接受入群邀请出错")
			}
		}).
		OnRoomJoin(func(context *wechaty.Context, room *user.Room, inviteeList []_interface.IContact, inviter _interface.IContact, date time.Time) {
			err := s.saveRoom(room, inviter, date)
			if err != nil {
				log.Println("保存群信息失败")
			}
			log.Printf("群信息已保存[roomId:%s]\n", room.ID())
		}).
		OnRoomLeave(func(context *wechaty.Context, room *user.Room, leaverList []_interface.IContact, remover _interface.IContact, date time.Time) {
		}).
		OnRoomTopic(func(context *wechaty.Context, room *user.Room, newTopic string, oldTopic string, changer _interface.IContact, date time.Time) {
			err := s.ChangeTopic(room, date)
			if err != nil {
				log.Println("更新群名称失败")
				return
			}
		}).
		OnMessage(func(context *wechaty.Context, message *user.Message) {
			if !message.Self() {
				log.Println("收到消息:" + message.String())
			}
		}).
		OnError(func(context *wechaty.Context, err error) {
			log.Printf("Wechaty服务发生错误[error:%s]\n", err.Error())
		})
	robots[qr] = robot
	robot.DaemonStart()
	return qr, nil
}

func (s *robotService) saveRoom(room *user.Room, inviter _interface.IContact, date time.Time) error {
	now := time.Now()
	var r = model.Room{
		Id:          room.ID(),
		Name:        room.Topic(),
		InviterId:   inviter.ID(),
		InviterName: inviter.Name(),
		JoinedTime:  date,
		CreatedTime: now,
		UpdatedTime: now,
	}
	return s.roomService.Save(r)
}

func (s *robotService) ChangeTopic(room *user.Room, date time.Time) error {
	var r = model.Room{
		Id:          room.ID(),
		Name:        room.Topic(),
		UpdatedTime: date,
	}
	return s.roomService.ChangeTopic(r)
}

func (s *robotService) save(user *user.ContactSelf) {
	avatar, err := user.Avatar().ToDataURL()
	if err != nil {
		log.Printf("获取头像失败[error:%s]\n", err.Error())
	}
	var robot = model.Robot{
		Id:       user.ID(),
		Gender:   int(user.Gender()),
		Type:     int(user.Type()),
		Name:     user.Name(),
		Avatar:   avatar,
		Alias:    user.Alias(),
		Province: user.Province(),
		City:     user.City(),
		Star:     user.Star(),
		WeiXin:   user.Weixin(),
	}
	err = s.repo.Insert(robot)
	if err != nil {
		log.Printf("保存机器人信息失败[error:%s]\n", err.Error())
	}
}
